﻿
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;

namespace MyBasicLib.Utilities
{

    /// <summary>
    /// 验证失败异常
    /// </summary>
    [Serializable]
    public class ValidationException : Exception
    {
        private string p;

        public ValidationException(string p)
            : base(p)
        {
        }

    }
    /// <summary>
    /// 验证辅助类
    /// </summary>
    public class ValidationHelper
    {

        /// <summary>
        /// 验证对象是否符合规则，当没有通过验证时抛出ValidationException
        /// </summary>
        /// <param name="obj">要验证的对象</param>
        public static void Valid(object obj)
        {
            var result = TryValid(obj);
            if (!result.Success)
            {
                throw new ValidationException(result.Message);
            }
        }
        /// <summary>
        /// 验证对象是否符合规则
        /// </summary>
        /// <param name="obj">要验证的对象</param>
        /// <returns>是否通过验证</returns>
        public static ExecutionResult TryValid(object obj)
        {
            List<ValidationResult> ds = new List<ValidationResult>();
            var ctx = new ValidationContext(obj, null, null);
            var s = Validator.TryValidateObject(obj, ctx, ds, true);
            return new ExecutionResult() { Success = s, Message = s ? string.Empty : ds[0].ErrorMessage };
        }
    }
    /// <summary>
    /// 执行结果
    /// </summary>
    [DataContract]
    public class ExecutionResult
    {
        public ExecutionResult() { }
        public ExecutionResult(Boolean success)
        {
            Success = success;
        }
        public ExecutionResult(Boolean success, String message)
        {
            Success = success;
            Message = message;
        }

        [DataMember]
        public Boolean Success { get; set; }
        [DataMember]
        public String Message { get; set; }
    }

    /// <summary>
    /// 执行结果
    /// </summary>
    /// <typeparam name="T">执行结果的实际类型</typeparam>
    [DataContract]
    [KnownType(typeof(ExecutionResult))]
    public class ExecutionResult<T> : ExecutionResult
    {
        public ExecutionResult() { }
        public ExecutionResult(ExecutionResult executionResult) : base(executionResult.Success, executionResult.Message) { }

        [DataMember]
        public T Data { get; set; }
    }

}
